import { useState } from "react";

import { Checkbox } from "../ui/checkbox";
import { IfElse } from "../IfElse/IfElse";
import { TaskCarddPhotoGallery } from "../TaskBoard/TaskCardPhotoGallery";
import { TaskSlider, TaskCardComments, SubTaskChecklist, TaskCardExecutor } from ".";
import { Button, ButtonProps } from "../ui/button";
import { TimeIcon } from "../Icons";
import { countingProgressbar } from "@/helpers";
import { ChevronDown, ListPlus, Trash, UserRoundPlus } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '../ui/dropdown-menu';
import { NewChecklist } from "../NewTask/NewChecklist";
import { AlertAnswer } from "../Customs";
import { useAppDispatch } from "@/hook/useRedux";
import { addFileTask, changeSubtaskDate, removeTaskItem, toggleStatusSubtask } from "@/redux/tasks/tasksSlice";
import clsx from "clsx";
import { VerticalProgressbar } from "../VerticalProgressbar";
import { FileSelector } from "../FileSelector/FileSelector";
import { TaskCardTags } from "./TaskCardTags";
import { SubtaskCardDate } from "./SubtaskCardDate";
import { DatePicker } from "../DatePicker/DatePicker";
import { AdvancedButton } from "../AdvancedButton/AdvancedButton";

interface Props {
  task: Task
}

export const SubtaskCard = ({ task }: Props) => {
  const [data] = useState<Task>(task);
  const [popupSliderIndex, setPopupSliderIndex] = useState(0);
  const [showComments, setShowComments] = useState(false);
  const [popupSlider, setPopupSlider] = useState(false);

  const [toggleShow, setToggleShow] = useState<boolean>(false)

  const [dropMenu, setDropMenu] = useState(false);
  const [subtaskDialog, setSubtaskDialog] = useState<boolean>(false);

  const [removeTask, setRemoveTask] = useState(false);
  const dispatch = useAppDispatch()

  const handleOpenDropMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    setDropMenu(!dropMenu);
  };

  const handleCheckboxClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    const isChecked = task.is_closed === 1 ? 0 : 1;
    dispatch(toggleStatusSubtask({
      subtaskId: task.id,
      colId: task.column_id,
      status: isChecked,
      taskId: task.parent_id
    }));
  };

  const activeSliderIndex = (index: number) => {
    setPopupSliderIndex(index);
    setPopupSlider(true);
  };

  const removeTaskCard = () => {
    dispatch(removeTaskItem({ id: data.id, columnId: data.column_id, parentId: data.parent_id }));
    setRemoveTask(false);
  };

  const successSubtask = task.subtasks.filter(it => !!it.is_closed)

  const sendFiles = async (uploadFiles: File[]) => {
    let formDataFiles = new FormData();
    formDataFiles.append('task_id', `${data.id}`);
    uploadFiles.forEach((file, i: number) => {
      formDataFiles.append(`files[${i}]`, file);
    });
    formDataFiles.append('gid', `${data.files_gid || ''}`);
    dispatch(addFileTask({ file: formDataFiles, taskId: data.parent_id, colId: data.column_id, subtaskId: data.id }));
  };

  const handleToggle = () => {
    const newToggleShow = !toggleShow;
    setToggleShow(newToggleShow);
  };


  type buttonProps = ButtonProps
  const btnMenuConfig: buttonProps = {
    className: 'flex w-full items-center justify-start gap-2 pl-2',
    variant: 'ghost',
  }

  const changeEndDate = (date: any) => {
    dispatch(changeSubtaskDate({ columnId: task.column_id, taskId: task.parent_id, date: date.end_date, subtaskId: task.id }))
  }

  return (
    <div className="w-[100%]" >
      <div className={clsx("group/subtask bg-[#F3F7FA] rounded-[16px] w-full p-5 ml-auto z-10 relative shadow-[0_4px_4px_0_rgba(202,219,234,1)]",)}>
        <header className="flex flex-col gap-2">
          <div className="flex items-center w-full  gap-[10px]" >
            <Checkbox
              onClick={handleCheckboxClick}
              checked={!!task.is_closed}
              className='mt-1  size-[18px] rounded-full border'
            />
            <AdvancedButton icon="Plus" className="ml-auto group-hover/subtask:text-[--btn-color-hover] text-[#f3f7fa]" onClick={(e) => {
              e.stopPropagation()
              setSubtaskDialog(true)
            }} />
            <DropdownMenu open={dropMenu} onOpenChange={setDropMenu}>
              <DropdownMenuTrigger onClick={handleOpenDropMenu} asChild >
                <AdvancedButton icon="EllipsesIcon" className="group-hover/subtask:text-[--btn-color-hover] text-[#f3f7fa]" onClick={(e) => e.stopPropagation()} />
              </DropdownMenuTrigger>
              <DropdownMenuContent onClick={(e) => e.stopPropagation()} className='p-2 bg-white border shadow-sm rounded-md z-50'>
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    setSubtaskDialog(true);
                    setDropMenu(false);
                  }}
                  variant={'ghost'}
                  className='flex w-full items-center justify-start gap-2'
                >
                  <ListPlus size={16} /> Чеклист
                </Button>
                <Button variant={'ghost'} className='flex w-full items-center justify-start gap-2'>
                  <UserRoundPlus size={16} /> Исполнитель
                </Button>
                <DatePicker setTaskDate={changeEndDate} end_date={task.end_date} clear={changeEndDate} side='right' >
                  <Button {...btnMenuConfig}>
                    <TimeIcon size={16} /> Дата
                  </Button>
                </DatePicker>
                <DropdownMenuSeparator />
                <Button
                  variant={'ghost'}
                  onClick={(e) => {
                    e.stopPropagation();
                    setDropMenu(false);
                    setRemoveTask(true);
                  }}
                  className='flex w-full items-center justify-start  gap-2'
                >
                  <Trash size={16} /> Удалить
                </Button>
              </DropdownMenuContent>
            </DropdownMenu>

          </div>
        </header>

        <IfElse>
          <IfElse.When isTrue={!!task.files.length} >
            <div className='py-4 pt-2'>
              <TaskCarddPhotoGallery files={task.files} onClick={activeSliderIndex} />
            </div>
          </IfElse.When>
        </IfElse>
        <TaskCardTags taskData={task} />
        <h2>{data.name}</h2>
        <div className='my-2 flex gap-2'>
          <div className='flex gap-4'>
            <TaskCardExecutor performers={data.performers} />
            <SubtaskCardDate endDate={task.end_date} taskId={task.parent_id} columnId={task.column_id} subtaskId={task.id} />
          </div>
          <div className='ml-auto flex gap-2'>
            <div className='flex items-center gap-1 text-slate-500'>
              <FileSelector setFiles={sendFiles} >
                <AdvancedButton icon="Files" variant={'base'} />
              </FileSelector>
              <AdvancedButton icon='Comments' iconCount={data.comments.count} iconNewCount={!!data.comments.new} variant={'base'} onClick={(e) => {
                e.stopPropagation()
                setShowComments(prev => !prev)
              }} />
            </div>
          </div>
        </div>
        <IfElse>
          <IfElse.When isTrue={showComments}>
            <TaskCardComments comments={data.comments} taskId={data.id} />
          </IfElse.When>
        </IfElse>
        <IfElse>
          <IfElse.When isTrue={!!task?.subtasks?.length} >
            <div className="flex flex-col" >
              <div className="flex flex-col ">
                <span className="text-[13px] text-[#384455]  -mb-2" >{successSubtask.length}/{task.subtasks.length}</span>
                <div className="flex items-center gap-2 " >
                  <VerticalProgressbar percent={countingProgressbar(task.subtasks || [])} />
                  <Button onClick={handleToggle} className={clsx("flex justify-center m-auto p-0 transition-transform text-slate-400",)} variant={'ghost'} >
                    <ChevronDown className={clsx('transition-all', toggleShow ? 'rotate-180' : '')} />
                  </Button>
                </div>
              </div>
            </div>
          </IfElse.When>
        </IfElse>
        <TaskSlider
          arr={task.files}
          open={popupSlider}
          setOpen={setPopupSlider}
          activeSliderIndex={popupSliderIndex}
        />
        <AlertAnswer open={removeTask} cancel={() => setRemoveTask(false)} accept={removeTaskCard} text={`Вы действительно хотите удалить колонну ${task.name}?`} />

        {subtaskDialog &&
          <NewChecklist
            columnId={data.column_id.toString()}
            parentId={data.id} grandParentId={data.parent_id}
            setOpen={setSubtaskDialog}
            aiShow={false} />
        }
      </div>
      {!!task.subtasks.length && toggleShow && <div className="py-2 cursor-default bg-[#F3F7FA] w-[90%] ml-auto mr-auto rounded-b-[16px]" onClick={(e) => e.stopPropagation()}>
        <IfElse>
          <IfElse.When isTrue={toggleShow}>
            <SubTaskChecklist data={task.subtasks} taskId={task.id} columnId={data.column_id} parentId={task.parent_id} />
          </IfElse.When>
        </IfElse>
      </div>
      }
    </div >
  )
}